#include "fonctions.h"



int main(int argc, char const *argv[]) {
    // Declaration variables.
    struct SocketTCP* socket;
    struct sockaddr_in server_adress;

    // Creation socket.
    socket = creatSocketTCP();
    // Initialisation socket.
    socket->new_addr->sin_family = AF_INET;
    socket->new_addr->sin_addr.s_addr = htonl(INADDR_ANY);
    socket->new_addr->sin_port = htons(0);

    // Bind.
    if(bind(socket->descripteur, (struct sockaddr *) socket->new_addr, socket->new_addr_len)) {
        perror("ERREUR: Client - bind.");
        return -1;
    }

    // Initialisation adresse serveur.
    server_adress.sin_family = AF_INET;
    if (inet_aton(argv[1], &(server_adress.sin_addr)) == 0){
        printf("ERROR: Client - Invalid IP address format <%s>.\n", argv[1]);
        return 1;
    }
    server_adress.sin_port = htons(SERVER_PORT);

    // Connect.
    if(f_connect(socket->descripteur, (struct sockaddr *) &server_adress, sizeof (struct sockaddr)) == -1) {
        perror("ERROR: Client - connect.");
        return -1;
    }
    server_adress.sin_port = htons(SERVER_PORT+10);
    // Communication.
    for(int i = 2; i < argc; ++i) {
        printf("dans le for client\n");
        //if (write(socket->descripteur, argv[i], strlen(argv[i])+1)== -1){
        if (sendto(socket->descripteur, argv[i], strlen(argv[i])+1, 0, (struct sockaddr *) &server_adress, sizeof (server_adress)) == -1) {
            perror("ERROR: Client - write.");
            return -1;
        } else {
            printf("Sent to %s: %s\n", argv[1], argv[i]);
        }
    }

    // Close.
    f_close(socket);
    return 0;
}